package org.xxpay.manage.channelmch.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.MD5Util;
import org.xxpay.core.common.util.StrUtil;
import org.xxpay.core.entity.*;

import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/channelmch_info")
public class ChannelMchInfoController extends BaseController {



    @Autowired
    private RpcCommonService rpcCommonService;
    /**
     * 查询渠道商信息
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long channelMchId = getLongRequired(param, "channelMchId");
        ChannelMchInfo channelMchInfo = rpcCommonService.rpcChannelMchInfoService.findBychannelMchId(channelMchId);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(channelMchInfo));
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        ChannelMchInfo channelMchInfo = getObject(param, ChannelMchInfo.class);
        int count = rpcCommonService.rpcChannelMchInfoService.count(channelMchInfo);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<ChannelMchInfo> channelMchInfoList = rpcCommonService.rpcChannelMchInfoService.select((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), channelMchInfo);
        List<JSONObject> objects = new LinkedList<>();
        for(ChannelMchInfo info : channelMchInfoList) {
            JSONObject object = (JSONObject) JSON.toJSON(info);
          object.put("loginChannelMchUrl", buildLoginChannelMchUrl(info));  // 生成登录地址
//            AgentAccount account = rpcCommonService.rpcAgentAccountService.findByAgentId(info.getChannelMchId());
//            object.put("agentBalance", account.getBalance());  // 账户余额

          //  PayPassage findById(Integer id);
            objects.add(object);
        }
        Map<String ,Object> ps = new HashMap<String, Object>();
//        AgentAccount accountRecord = new AgentAccount();
//        accountRecord.setAgentId(channelMchInfo.getChannelMchId());
//        ps.put("allAgentBalance",  rpcCommonService.rpcAgentAccountService.sumAgentBalance(accountRecord));
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects, ps, count));
    }

    /**
     * 新增代理商信息
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增渠道商" )
    public ResponseEntity<?> add(HttpServletRequest request, ChannelMchInfo channelMchInfo) {
      //  JSONObject param = getJsonParam(request);
     //   ChannelMchInfo channelMchInfo = getObject(param, ChannelMchInfo.class);
        System.out.println("----------------"+channelMchInfo.toString());
        // 设置默认登录密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = MchConstant.CHANNELMCH_DEFAULT_PAY_PASSWORD;
        channelMchInfo.setPassword(encoder.encode(rawPassword));
        channelMchInfo.setLastPasswordResetTime(new Date());
        // 设置默认支付密码
        String payPassword = MchConstant.CHANNELMCH_DEFAULT_PAY_PASSWORD;
        channelMchInfo.setPayPassword(MD5Util.string2MD5(payPassword));
        // 确认用户名不能重复
        if(rpcCommonService.rpcChannelMchInfoService.findByUserName(channelMchInfo.getUserName()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_AGENT_USERNAME_USED));
        }
        // 确认手机不能重复
        if(rpcCommonService.rpcChannelMchInfoService.findByMobile(channelMchInfo.getMobile()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_MOBILE_USED));
        }
        // 确认邮箱不能重复
        if(rpcCommonService.rpcChannelMchInfoService.findByEmail(channelMchInfo.getEmail()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_EMAIL_USED));
        }

//        // 验证一级代理ID
//        if (agentInfo.getParentAgentId() == null) agentInfo.setParentAgentId(0L);
//        if(agentInfo.getParentAgentId() != 0) {
//            if (rpcCommonService.rpcAgentInfoService.findByAgentId(agentInfo.getParentAgentId()) == null) {
//                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PARENTAGENTID_NOT_EXIST));
//            }
//            if(rpcCommonService.rpcAgentInfoService.findByAgentId(agentInfo.getParentAgentId()).getAgentLevel() != 1){
//                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PARENTAGENTID_NOT_EXIST));
//            }
//            agentInfo.setAgentLevel((byte) 2);
//        }else{
//            agentInfo.setAgentLevel((byte) 1);
//        }

        int count = rpcCommonService.rpcChannelMchInfoService.add(channelMchInfo);
        if(count != 1) ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }


    /**
     * 删除
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @MethodLog( remark = "删除渠道商" )
    public ResponseEntity<?> delete(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String channelMchIds = getStringRequired(param, "channelMchIds");
        String[] ids = channelMchIds.split(",");
        List<Long> rids = new LinkedList<>();
        for(String channelMchId : ids) {
            if(NumberUtils.isDigits(channelMchId)) rids.add(Long.parseLong(channelMchId));
        }
        //  int batchDeleteRole(List<Long> roleIds);
        rpcCommonService.rpcChannelMchInfoService.batchDeleteChannelMch(rids);
     // rpcCommonService.rpcSysService.batchDeleteRole(rids);
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }
    @RequestMapping("/updateStatus")
    @ResponseBody
    @MethodLog( remark = "修改渠道商状态" )
    public ResponseEntity<?> updateStatus(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String channelMchId = getStringRequired(param, "channelMchId");
        String status = getStringRequired(param, "status");
        ChannelMchInfo channelMchInfo = new ChannelMchInfo();
        System.out.println("=====channelMchId===="+channelMchId);
        System.out.println("=====status===="+status);
        channelMchInfo.setChannelMchId(Long.valueOf(channelMchId));
        Byte channelMchStatus;
        if(status.equals("true")){
            channelMchStatus=1;
        }else {
            channelMchStatus=0;
        }
        channelMchInfo.setStatus(channelMchStatus);
        rpcCommonService.rpcChannelMchInfoService.update(channelMchInfo);

        return ResponseEntity.ok(BizResponse.buildSuccess());
    }




    private String buildLoginChannelMchUrl(ChannelMchInfo channelMchInfo) {
        // 将商户ID+商户密码+密钥 做32位MD5加密转大写,作为token传递给商户系统
        String password = channelMchInfo.getPassword();
        String secret = "Abc%$G&!!!128G";
        String rawToken = channelMchInfo.getChannelMchId() + password + secret;
        String token = MD5Util.string2MD5(rawToken).toUpperCase();
        String loginChannelMchUrl = mainConfig.getLoginChannelMchUrl();
        return String.format(loginChannelMchUrl, channelMchInfo.getChannelMchId(), token);
    }
}